function basePath() {
    var curWwwPath = window.document.location.href;
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    var localhostPath = curWwwPath.substring(0, pos);
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
    return (localhostPath + projectName);
}

loading();

var page_now = 0;
//题目类型 0/选择题   1/解答题或者编程题
var question_type = 0;

$(function () {
    getAllCourse();
    getQuestionList(1);
    validatorA();
    bqtitle = CKEDITOR.replace('b_quetitle');
    bqans = CKEDITOR.replace('b_ans');
    quetitle = CKEDITOR.replace('quetitle');

});

//获取所有课程
function getAllCourse() {
    $.ajax({
        url: basePath() + "/teacher/exam/get_course.do",
        type: 'GET',
        dataType: 'JSON',
        success: function (data) {
            for (var i = 0; i < data.data.length; i++) {
                var option = "<option value='" + data.data[i].id + "'>" + data.data[i].name + "</option>";
                $(".loadincourseid").append(option);
                $(".loadincourseid1").append(option);
            }
        }
    })
}


function validatorA() {
    $('#updateForm').bootstrapValidator({
        message: 'is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            quetitle: {
                message: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '题干不能为空'
                    }
                }
            },
            choicea: {
                messageL: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '答案a不能为空'
                    }
                }
            },
            choiceb: {
                messageL: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '答案b不能为空'
                    }
                }
            },
            choicec: {
                messageL: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '答案c不能为空'
                    }
                }
            },
            choiced: {
                messageL: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '答案d不能为空'
                    }
                }
            }

        }
    });
}

//获取选择题库
function getQuestionList(page_num) {
    var courseName = $("#courseName").val();
    var questionTitle = $("#questionTitle").val();
    page_now = page_num;
    question_type = 0;
    $("#outin").removeAttr("style");
    $("#outinbq").hide();
    page_now = page_num;
    $.ajax({
        url: basePath() + '/teacher/question/show_all_questions.do',
        type: 'GET',
        async: 'true',
        data: {
            "pageNum": page_num,
            "pageSize": "10",
            "questionTitle":questionTitle,
            "courseName":courseName
        },
        dataType: 'json',
        success: function (data) {
            removeLoading();
            //serverResponse里放pageinfo 在这直接获取data就是整个data
            var page = data.data;
            //获取放入pageinfo的List 用到分页的一定是list List是默认的属性名
            var item = data.data.list;
            //根据总页数和当前页数进行分页  第一个参数是当前页数  第二个是总页数  都是 pageinfo给的
            setPage(page.pageNum, page.pages, "getQuestionList");
            //把获取的数据放入这个id的区域
            $("#result").html("");
            $("#big_result").html("");

            //隐藏大题表格的标题
            $('#bigquestiontitle').css('display', 'none');

            for (var i = 0; i < item.length; i++) {
                //克隆这个模板 然后在填充数据 jquery 方法
                var title = $("#questionstitle");
                title.removeAttr("style");
                var temp = $("#m_template").clone();
                //给那个模板进行id的改变 让他不重复
                temp.attr("id", item[i].id);
                //开始是隐藏样式 移除这个样式
                temp.removeAttr("style");
                //设置序号  可以不一样
                temp.find(".q_num").html(item[i].id);
                //find方法就是把值给他根据属性名
                temp.find(".c_id").html(item[i].courseName);
                temp.find(".q_title").html(item[i].quetitle);
                temp.find((".q_A")).html(item[i].choicea);
                temp.find((".q_B")).html(item[i].choiceb);
                temp.find((".q_C")).html(item[i].choicec);
                temp.find((".q_D")).html(item[i].choiced);
                temp.find((".q_ans")).html(item[i].ans);
                //用于大题
//                        var m_type = '';
//                        if (item[i].type == 1) {
//                            m_type = '开发';
//
                //修改按钮组装
                var up_btn = "<button type='button'  class='btn btn-primary btn-xs btn-warning' onclick='updateQuestios(" + item[i].id + ");' ><span class='glyphicon glyphicon-edit' aria-hidden='true'></span><span style='margin: 0px 8px;'>修改</span></button>"
                temp.find(".q_update").html(up_btn);
                //这个this是什么
                var op_btn = "<button type='button'  class='btn btn-primary btn-xs btn-danger' onclick='deleteQustions(this);' ><span class='glyphicon glyphicon-remove' aria-hidden='true'></span><span style='margin: 0px 8px;'>删除</span></button>"
                temp.find(".q_delete").html(op_btn);
                //插入结果
                $("#result").append(temp);
            }
        }
    })
}

function deleteQustions(what) {
    //判断是否确认删除
    bootbox.setDefaults('locale', 'zh_CN');
    bootbox.confirm("确认删除?", function (res) {
        if (res) {
            //因为tr的id已经变成了每条记录的id所以可以直接用
            var q_id = $(what).parent().parent().attr("id");
            $.ajax({
                url: basePath() + '/teacher/question/delete_questions.do',
                method: 'POST',
                async: true,
                data: {
                    "id": q_id
                },
                dataType: 'json',
                success: function (data) {
                    bootbox.alert(data.msg);
                    getQuestionList(1);
                }
            })
        }
    });
}

function commitUpdate() {
    var bv = $("#updateForm").data('bootstrapValidator');
    bv.validate();
    if (!bv.isValid()) {
        return;
    }
    var title = CKEDITOR.instances.quetitle.getData();
    if (title == "") {
        bootbox.alert("题干不能为空");
        return;
    }
    var qid = $("#id").val();

    var a = $("#choicea").val();
    var b = $("#choiceb").val();
    var c = $("#choicec").val();
    var d = $("#choiced").val();
    var ans = $("#ans").val();
    var cid = $("#courseid").val();
    $.ajax({
        url: basePath() + '/teacher/question/update_questions.do',
        method: 'POST',
        async: true,
        data: {
            "id": qid,
            "quetitle": title,
            "choicea": a,
            "choiceb": b,
            "choicec": c,
            "choiced": d,
            "ans": ans,
            "courseid": cid
        },
        dataType: 'json',
        success: function (data) {
            bootbox.alert(data.data);
            clearSmallModal();
            getQuestionList(page_now);
        }
    })
}

function updateQuestios(q_id) {
    $.ajax({
        url: basePath() + '/teacher/question/edit_questions.do',
        method: 'POST',
        async: true,
        data: {
            "id": q_id
        },
        dataType: 'json',
        success: function (data) {
            if (data.msg == "修改") {
                $("#courseid option").remove()
                //设置他的值
                var option = "<option value =" + data.data.question.courseid + ">" + '默认不修改' + "</optin>"
                $("#courseid").append(option);
                for (var i = 0; i < data.data.allCourse.length; i++) {
                    option = "<option value =" + data.data.allCourse[i].id + ">" + data.data.allCourse[i].name + "</optin>"
                    $("#courseid").append(option);
                }
                quetitle.setData(data.data.question.quetitle);
                $("#choicea").val(data.data.question.choicea);
                $("#choiceb").val(data.data.question.choiceb);
                $("#choicec").val(data.data.question.choicec);
                $("#choiced").val(data.data.question.choiced);
                if (data.data.question != "") {
                    $("#ans option:contains('" + data.data.question.ans + "') ").prop("selected", "true");
                }
                $("#id").val(q_id);
                $("#changQuestion").modal("show");

            } else {
                $("#courseid option").remove();
                for (var i = 0; i < data.data.allCourse.length; i++) {
                    var option = "<option value =" + data.data.allCourse[i].id + ">" + data.data.allCourse[i].name + "</optin>"
                    $("#courseid").append(option);
                }
                quetitle.setData("");
                $("#choicea").val("");
                $("#choiceb").val("");
                $("#choicec").val("");
                $("#choiced").val("");
                $("#id").val(null);
                $("#changQuestion").modal("show");
                $("#ans option[value = 'A']").prop("selected", true);
            }
        }
    })
}

//大题
function getBigQuestionList(page_num) {
    page_now = page_num;
    question_type = 1;
    var bqcourseName = $("#bqcourseName").val();
    var bqquestionTitle = $("#bqquestionTitle").val();
    $("#outin").hide();
    $("#outinbq").removeAttr("style");
    page_now = page_num;
    $.ajax({
        url: basePath() + '/teacher/bigquestion/show_all_bigquestions.do',
        type: 'GET',
        async: 'true',
        data: {
            "pageNum": page_num,
            "pageSize": "5",
            "bqquestionTitle":bqquestionTitle,
            "bqcourseName":bqcourseName
        },
        dataType: 'json',
        success: function (data) {
            //serverResponse里放pageinfo 在这直接获取data就是整个data
            var page = data.data;
            //获取放入pageinfo的List 用到分页的一定是list List是默认的属性名
            var item = data.data.list;
            //根据总页数和当前页数进行分页  第一个参数是当前页数  第二个是总页数  都是 pageinfo给的
            setPage(page.pageNum, page.pages, "getBigQuestionList");
            //把获取的数据放入这个id的区域
            $("#big_result").html("");
            $("#result").html("");

            //隐藏选择题表格的标题
            $('#questionstitle').css('display', 'none');

            for (var i = 0; i < item.length; i++) {
                var title = $("#bigquestiontitle");
                title.removeAttr("style");
                var temp = $("#big_m_template").clone();
                temp.attr("id", item[i].id);
                temp.removeAttr("style");
                temp.find(".bq_num").html(item[i].id);
               temp.find(".bq_c_id").html(item[i].courseName);
                temp.find(".bq_title").html(item[i].title);
                temp.find((".bq_ans")).html(item[i].contentans);
                //用于大题
                var bq_type = '编程题';
                if (item[i].type == 1) {
                    bq_type = '简答题';
                }
                temp.find(".bq_type").html(bq_type);
                var up_btn = "<button type='button'  class='btn btn-primary btn-xs btn-warning' onclick='updateBigQuestion(" + item[i].id + "," + item[i].type + ");' ><span class='glyphicon glyphicon-edit' aria-hidden='true'></span><span style='margin: 0px 8px;'>修改</span></button>"
                temp.find(".bq_update").html(up_btn);
                var op_btn = "<button type='button'  class='btn btn-primary btn-xs btn-danger' onclick='deleteBigQuestion(" + item[i].id + ");' ><span class='glyphicon glyphicon-remove' aria-hidden='true'></span><span style='margin: 0px 8px;'>删除</span></button>"
                temp.find(".bq_delete").html(op_btn);
                $("#big_result").append(temp);
            }
        }
    })
}

function commitBUpdate() {
    var id = $("#b_id").val();
    var title = bqtitle.getData();
    var ans = bqans.getData();
    if (title == "" || ans == "") {
        bootbox.alert("题干或者答案不能为空");
        return;
    }
//            var title = $("#b_quetitle").val();
//            var ans = $("#b_ans").val();
    var cid = $("#b_courseid").val();
    var type = $("#bigQuestionType").val();
    $.ajax({
        url: basePath() + '/teacher/bigquestion/update_bigquestion.do',
        async: true,
        method: 'POST',
        data: {
            "id": id,
            "courseid": cid,
            'title': title,
            'contentans': ans,
            'type': type
        },
        dataType: 'JSON',
        success: function (data) {
            bootbox.alert(data.data);
            clearBigModal();
            getBigQuestionList(page_now);
        }
    })
}

function updateBigQuestion(bq_id, type) {
    $.ajax({
        url: basePath() + '/teacher/bigquestion/edit_bigquestion.do',
        method: 'POST',
        async: true,
        data: {
            "id": bq_id
        },
        dataType: 'json',
        success: function (data) {
            if (data.msg == "修改") {
                //设置他的值
                $("#b_courseid option").remove();
                var option;
                option = "<option value = " + data.data.bigQuestion.courseid + ">" + '默认不修改' + "</option>"
                $("#b_courseid").append(option);
                for (var i = 0; i < data.data.allCourse.length; i++) {
                    option = "<option value = " + data.data.allCourse[i].id + ">" + data.data.allCourse[i].name + "</option>"
                    $("#b_courseid").append(option);
                }
                $("#bigQuestionType").val(type);
                bqtitle.setData(data.data.bigQuestion.title);
                bqans.setData(data.data.bigQuestion.contentans);
                $("#b_id").val(bq_id);
                $("#changBigQuestion").modal("show");
            } else {
                $("#b_courseid option").remove();
                var option;
                for (var i = 0; i < data.data.allCourse.length; i++) {
                    option = "<option value = " + data.data.allCourse[i].id + ">" + data.data.allCourse[i].name + "</option>"
                    $("#b_courseid").append(option);
                }
                bqtitle.setData("");
                bqans.setData("");
                $("#b_id").val(null);
                $("#changBigQuestion").modal("show");
            }
        }
    })
}

function deleteBigQuestion(bq_id) {
    bootbox.setDefaults('locale', 'zh_CN');
    bootbox.confirm("确认删除?", function (res) {
        if (res) {
            $.ajax({
                url: basePath() + '/teacher/bigquestion/delete_bigquestion.do',
                method: 'POST',
                async: true,
                data: {
                    "id": bq_id
                },
                dataType: 'json',
                success: function (data) {
                    bootbox.alert("删除成功");
                    getBigQuestionList(1);
                }
            })
        }
    });
}


function clearBigModal() {
    $('#changBigQuestion').modal('hide');
    $('#b_quetitle').val("");
    $('#b_ans').val("");

    // $('#updateBigForm').data('bootstrapValidator').destroy();
    // $('#updateBigForm').data('bootstrapValidator', null);
    // $("form[id='updateBigForm'] > div").addClass('has-success');
    // validatorA();.
}


function clearSmallModal() {
    $('#changQuestion').modal('hide');
    $('#quetitle').val("");
    $('#choicea').val("");
    $('#choiceb').val("");
    $('#choicec').val("");
    $('#choiced').val("");
    $('#ans').val("");

    $('#updateForm').data('bootstrapValidator').destroy();
    $('#updateForm').data('bootstrapValidator', null);
    $("form[id='updateForm'] > div").addClass('has-success');
    validatorA();
}

function loadOutExcel() {

    var url = basePath() + "/teacher/question/get_question_title_excel.do";

    window.location.href = url;
}

function loadOutBQExcel() {
    var url = basePath() + "/teacher/bigquestion/get_bquestion_title_excel.do";

    window.location.href = url;
}

function toUploadBQ() {
    var courseId = $(".loadincourseid1").val();
    var queType = $("#loadinquetype").val();
    if (courseId == -1 || queType == 0) {
        bootbox.alert("没有选择导入题目的课程,或没有选择导入的题型");
    } else {
        var dialog = bootbox.dialog({
            title: '请稍候',
            message: '<i class="icon-spinner icon-spin icon-2x pull-left"></i> 导入中...</p>'
        });

        $('#uploadForm2').ajaxSubmit({
            url: basePath() + '/teacher/bigquestion/load_in_bigquestion.do',
            type: 'post',
            async: true,
            cache: false,
            contentType: false,
            processData: false,
            data: {
                "courseId": courseId,
                "queType": queType
            },
            dataType: 'json',
            success: function (res) {
                if (res.success) {
                    dialog.find('.modal-title').html('完成');
                    dialog.find('.modal-body').html(res.msg);
                    dialog.find('.modal-body').after("<div class=\"modal-footer\"><button data-bb-handler=\"ok\" type=\"button\" class=\"btn btn-primary\">OK</button></div>");
                    getBigQuestionList(1);
                } else {
                    dialog.find('.modal-title').html('错误');
                    dialog.find('.modal-body').html(res.msg);
                    dialog.find('.modal-body').after("<div class=\"modal-footer\"><button data-bb-handler=\"ok\" type=\"button\" class=\"btn btn-primary\">OK</button></div>");

                }
            },
            error: function () {
                dialog.find('.modal-title').html('失败');
                dialog.find('.modal-body').html("导入失败, 请稍后重试");
                dialog.find('.modal-body').after("<div class=\"modal-footer\"><button data-bb-handler=\"ok\" type=\"button\" class=\"btn btn-primary\">OK</button></div>");
            }

        });
    }
}

function toUpload() {
    var courseId = $(".loadincourseid").val();
    if (courseId == -1) {
        bootbox.alert("没有选择导入题目的课程");
    } else {
        var dialog = bootbox.dialog({
            title: '请稍候',
            message: '<i class="icon-spinner icon-spin icon-2x pull-left"></i> 导入中...</p>'
        });

        $('#uploadForm').ajaxSubmit({
            url: basePath() + '/teacher/question/load_in_question.do',
            type: 'post',
            async: true,
            cache: false,
            contentType: false,
            processData: false,
            data: {
                "courseId": courseId
            },
            dataType: 'json',
            success: function (res) {
                if (res.success) {
                    dialog.find('.modal-title').html('完成');
                    dialog.find('.modal-body').html(res.msg);
                    dialog.find('.modal-body').after("<div class=\"modal-footer\"><button data-bb-handler=\"ok\" type=\"button\" class=\"btn btn-primary\">OK</button></div>");
                    getQuestionList(1);
                } else {
                    dialog.find('.modal-title').html('错误');
                    dialog.find('.modal-body').html(res.msg);
                    dialog.find('.modal-body').after("<div class=\"modal-footer\"><button data-bb-handler=\"ok\" type=\"button\" class=\"btn btn-primary\">OK</button></div>");

                }
            },
            error: function () {
                dialog.find('.modal-title').html('失败');
                dialog.find('.modal-body').html("导入失败, 请稍后重试");
                dialog.find('.modal-body').after("<div class=\"modal-footer\"><button data-bb-handler=\"ok\" type=\"button\" class=\"btn btn-primary\">OK</button></div>");
            }

        });
    }
}
